package cn.bossx.basic.controller;

import cn.bossx.basic.util.AjaxResult;
import cn.bossx.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file) {

        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String uploadPath = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(uploadPath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败~~~~~~");
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path) { // /group1/M00/00/11/rBEABV9dxpCAQp4VAAD2Tqb_qxw838.jpg

        try {
            String pathTmp = path.substring(1); // group1/M00/00/11/rBEABV9dxpCAQp4VAAD2Tqb_qxw838.jpg
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/")); // group1
            String fileName = pathTmp.substring(pathTmp.indexOf("/") + 1); // M00/00/11/rBEABV9dxpCAQp4VAAD2Tqb_qxw838.jpg
            FastDfsUtil.delete(groupName, fileName);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败~~~~~~");
        }
    }

}
